package com.personal.system.listener;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.personal.common.result.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@Slf4j
public class PageLogInterceptor implements HandlerInterceptor {

    private static final String TRACE_ID = "TRACE_ID";
    private static final String PAGE_NO = "pageNo";
    private static final String PAGE_SIZE = "pageSize";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        log.info("LogInterceptor> {}", request.getServletPath());
        String tid = UUID.randomUUID().toString(true);
        if (StrUtil.isNotBlank(request.getHeader(TRACE_ID))){
            tid = request.getHeader(TRACE_ID);
        }

        // 诊断上下文映射，是@Slf4j提供的一个支持动态打印日志信息的工具。
        // 在 logback-base.xml中的控制台和输出日志中加 [%X{TRACE_ID}]
        MDC.put(TRACE_ID, tid);
        String currentPage = request.getParameter(PAGE_NO);
        String pageSize = Optional.ofNullable(request.getParameter(PAGE_SIZE)).orElse("10");
        if (StringUtils.isNoneBlank(currentPage)) {
            PageUtils.setCurrentPage(new Page<>(Long.parseLong(currentPage), Long.parseLong(pageSize)));
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        MDC.clear();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        MDC.remove(TRACE_ID);
    }
}
